package com.eportal.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import com.eportal.dao.TCommunityEntityMapper;
import com.eportal.vo.controller.background.community.TCommunitySelectVO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.aop.LogAnnotation;
import com.eportal.api.MdOpenAddCommunityJson;
import com.eportal.api.MdOpenApi;
import com.eportal.base.BaseDAO;
import com.eportal.domain.AppStore;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.domain.TCommunity;
import com.eportal.domain.TLock;
import com.eportal.domain.TUsers;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.service.AppStoreService;
import com.eportal.service.SysOptService;
import com.eportal.service.SysRolesTemplateService;
import com.eportal.service.TAgentService;
import com.eportal.service.TCommunityService;
import com.eportal.service.TKeysService;
import com.eportal.service.TLocksService;
import com.eportal.service.TUsersService;
import com.eportal.util.DateUtils;
import com.eportal.util.MD5;
import com.eportal.util.ValidateUtil;
import com.framework.jqgrid.JqGridPager;

/**
 * @author chencheng
 */
@Service("tCommunityService")
public class TCommunityServiceImpl implements TCommunityService {
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(TCommunityServiceImpl.class.getName());

	 @Autowired
	private TAgentService tAgentService;
	 @Autowired
	 private TLocksService tLocksService;
	@Autowired
	private SysRolesTemplateService sysRolesTemplateService;
	@Autowired
    private SysOptService sysOptService;
	@Autowired
	private AppStoreService appStoreService;
	@Autowired
	private TUsersService tusersService;
	@Autowired
	private TKeysService tKeysService;

	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private TCommunityEntityMapper tCommunityDao;

	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }

	@Override
	public List<TCommunity> list(JqGridPager jqGridPager) {
		 String sql = "select t.sid,t.agtcode,a.agtname,t.areacode,t.citycode,t.communityname,bds.bdNum,units.unitNum,rms.roomNum,us.userNum,ope.openNum,op.visitorNum  from T03_COMMUNITY t "
		 		+ "left join t02_agtent a on t.agtcode=a.agtcode "
		 		+ "left join (select u.communityid,count(u.sid) as userNum from t04_users_community u where u.status=1 group by u.communityid) us on t.sid=us.communityid "
		 		+ "left join (select rm.communityid, count(rm.sid) as roomNum from T035_ROOM rm group by rm.communityid) rms on t.sid = rms.communityid "
		 		+ "left join (select bd.communityid, count(bd.sid) as bdNum from T031_CBUILDING bd group by bd.communityid) bds on t.sid = bds.communityid "
		 		+ "left join (select sum(unitNumber) as unitNum, communityid from (select count(t1.sid) unitNumber,t2.sid,t2.communityid from t032_cinstallunit t1, t031_cbuilding t2 where t1.cbuildingid = t2.sid group by t2.sid, t2.communityid) group by communityid) units on t.sid = units.communityid "
		 		+ "left join (select o.communityid,count(sid) as openNum from topenlog o group by o.communityid) ope on t.sid=ope.communityid "
		 		+ "left join (select o.communityid,count(sid) as visitorNum from topenlog o where o.opentype='0' group by o.communityid) op on t.sid=op.communityid ";
	        return dao.query(sql, jqGridPager);
	}

	@Override
	public TCommunity get(Long sid) {
		return (TCommunity) dao.getById(TCommunity.class, sid);
	}
	 @Override
	    public Object getObject(String sql) {
			return  dao.loadObject(sql);
		}

	    @Override
	    public void update(Object entity) throws Exception {
	    	try {
	    		dao.update(entity);
	        } catch (Exception e) {
	            log.error(this,e);
	        }

	    }
	@Override
	public Map<String, String> getBySql(Long sid) {
		List<Map<String, String>> list= null;
		StringBuilder sql = new StringBuilder("select t.*,s.username,a.agtname,app.appname from t03_community t  "
				+ "left join sysopt s on t.adminuser=s.sid "
				+ "left join t02_agtent a on t.agtcode=a.agtcode "
				+ "left join t10_appstore  app on t.appid=app.appid where t.sid=");
		sql.append(sid);
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public void delete(Long sid) {
		TCommunity role = (TCommunity) dao.getById(TCommunity.class, sid);
		dao.delete(role);

	}

	@Override
	public void update(TCommunity tCommunity) throws Exception {
		dao.update(tCommunity);
	}

	@Override
	public void delete(List<Long> ids) {
		for (Long id : ids) {
            delete(id);
        }
	}

	@Override
	public TCommunity add(TCommunity tCommunity) throws Exception {
		dao.save(tCommunity);
        return tCommunity;
	}

	/**
     * 社区新增保存
     */
    @LogAnnotation(operateDescribe="社区新增")
    public Map<String, Object> addMethod(TCommunity tCommunity){
        String msg = ValidateUtil.validate(tCommunity);
        if (msg == null || msg.trim().length() == 0) {
            try {
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");

            	tCommunity.setAgtCode(user.getAgtCode());
            	tCommunity.setcUserName(Long.toString(user.getSid()));
            	tCommunity.setcTime(new Timestamp(System.currentTimeMillis()));
                add(tCommunity);
                result.put("objectId", tCommunity.getSid());
                result.put("code", 1);
                result.put("msg", "操作成功");
            } catch (Exception e) {
                log.error("社区保存失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
            result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }

    /**
     * 社区修改保存
     */
    @LogAnnotation(operateDescribe="社区修改")
    public Map<String, Object> updateMethod(TCommunity tCommunity,String adminUserName, String password){
        String msg = ValidateUtil.validate(tCommunity);
        result.put("objectId", tCommunity.getSid());
        if (msg == null || msg.trim().length() == 0) {
            try {
            	TCommunity entity = get(tCommunity.getSid());
            	if (StringUtils.isNotBlank(tCommunity.getCommunityName())) {
            		entity.setCommunityName(tCommunity.getCommunityName());
            		entity.setDepartName(tCommunity.getCommunityName());
				}
            	if (StringUtils.isNotBlank(tCommunity.getDepartTel())) {
            		entity.setDepartTel(tCommunity.getDepartTel());
            	}
            	if (StringUtils.isNotBlank(tCommunity.getComContact())) {
            		entity.setComContact(tCommunity.getComContact());
            	}
            	if (StringUtils.isNotBlank(tCommunity.getAreaCode())) {
            		entity.setAreaCode(tCommunity.getAreaCode());
            		entity.setCityCode(tCommunity.getCityCode());
            	}
            	if (StringUtils.isNotBlank(tCommunity.getStreet())) {
            		entity.setStreet(tCommunity.getStreet());
            	}
            	if (StringUtils.isNotBlank(tCommunity.getDepartMail())) {
            		entity.setStreet(tCommunity.getDepartMail());
            	}
            	if ("2".equals(entity.getStatus())) {
        			entity.setStatus("0");
    			}
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	entity.setuUserName(Long.toString(user.getSid()));
            	entity.setuTime(new Timestamp(System.currentTimeMillis()));
                update(entity);
                if (StringUtils.isNotBlank(adminUserName) || StringUtils.isNotBlank(password) ) {
                	Sysopt sysopt = sysOptService.get(Long.parseLong(entity.getAdminUser()));
                	if (StringUtils.isNotBlank(adminUserName)){
                		sysopt.setUserName(adminUserName);
					}
                	if (StringUtils.isNotBlank(password)) {
                		sysopt.setPasswd(MD5.MD5Encode(password));
					}
                	sysOptService.update(sysopt);
				}
                result.put("code", 1);
                result.put("msg", "操作成功");
            } catch (Exception e) {
                log.error("社区更新失败", e);
                result.put("code", 0);
                result.put("msg", "操作失败");
            }
        } else {
            result.put("code", 0);
            result.put("msg", msg);
        }
        return result;
    }

	 /**
     * 社区删除
     */
    @LogAnnotation(operateDescribe="社区删除")
    public Map<String, Object> deleteMethod(String param_ids) {
        try {
        	result.put("objectId", param_ids);
            List<Long> ids = new LinkedList<Long>();
            for (String s : param_ids.split(",")) {
                ids.add(Long.parseLong(s));
            }
            delete(ids);
            result.put("code", 1);
            result.put("msg", "操作成功");
        } catch (Exception e) {
            log.error("社区删除失败", e);
            result.put("code", 0);
            result.put("msg", "操作失败");
        }
        return result;
    }

	@Override
	public List<TCommunity> list(String hql) {
		return dao.query(hql);
	}


	@Override
	public List<Map<String, Object>> listBySql(String sql) {
		return dao.queryBySql(sql);
	}


	@Override
	@LogAnnotation(operateDescribe="社区注册提交")
	public Map<String, Object> tComuAddMethod(TCommunity tCommunity) {
		String roleId = "3";//社区未审核通过角色
		String status="0";//未审核状态
		result = addtCommunity(tCommunity,roleId,status,"1");
		 return result;
	}

	@Override
	 @LogAnnotation(operateDescribe="锁厂客户注册提交")
	public Map<String, Object> tComuLockAddMethod(TCommunity tCommunity, String pid, String checkCode,String lockName, String type,String typeAPP,String appid,String pwd) {
		 try {
			 String resultUserid=null;
			 String resultToken=null;
			 result = new HashMap<String, Object>();
			 TLock tLock = null;
			 boolean ifInstall = false;
			if(StringUtils.isBlank(pid)){
				result.put("code", 0);
                result.put("msg", "查询不到此pid，请检查后重新输入");
                return result;
	        }else{
	        	StringBuilder sb = new StringBuilder();
         		sb.append("from TLock where pid ='");
         		sb.append(pid);
         		sb.append("'");
         		tLock = (TLock) getObject(sb.toString());
         		if(tLock == null){
         			result.put("code", 0);
                    result.put("msg", "查询不到此pid，请检查后重新输入");
                    return result;
         		}
         		if(!"1".equals(tLock.getCheckStatus())){
         			result.put("code", 0);
                    result.put("msg", "该硬件未检测或检查不通过，无法注册");
                    return result;
         		}
         		if(!checkCode.equals(tLock.getCheckCode())){
         			result.put("code", 0);
                    result.put("msg", "锁的激活码不匹配，请检查后请重新输入");
                    return result;
         		}
         		if(!"2".equals(type)){//需要转移的硬件，不需要验证是否已经安装
         			if("1".equals(tLock.getStatus())){//已被安装
             			result.put("code", 0);
                        result.put("msg", "该智能锁已被注册使用，请重新核对信息");
                        return result;
             		}
         		}
         		
         		if(appid!=null){
         			AppStore appStore = (AppStore)dao.getUniqueFirst("from AppStore where appid='"+appid+"'");
         			if(appStore!=null){
         				if(appStore.getAgtCode()!=null&&!appStore.getAgtCode().equals(tLock.getAgtCode())){
         					result.put("code", 0);
                            result.put("msg", "智能锁状态不符合安装要求，请联系商家");
                            return result;
         				}
         			}
         		}

         		ifInstall =true;
	        }
			tCommunity.setAgtCode(tLock.getAgtCode());
			tCommunity.setInviteUrl("锁厂客户验证PID注册，无注册码");
			TUsers tuser =  null;
			if("0".equals(typeAPP)){//app注册){
				String userId = (String) getSession().getAttribute("app_userid");
				if(userId==null){
					TUsers user = tusersService.getByWhere("tel='"+tCommunity.getDepartTel()+"' and appid='"+appid+"'");
					String token  = UUID.randomUUID().toString();
					if(user==null){
						String tel = tCommunity.getDepartTel();
						tuser = new TUsers();
						tuser.setTel(tel);
						tuser.setAppId(appid);
						tuser.setAuName(tCommunity.getCommunityName());
						tuser.setNickName(tel.substring(tel.length()-4,tel.length()));
						tuser.setAgtCode(tCommunity.getAgtCode());
						tuser.setAuTel(tel);
						tuser.setcTime(new Timestamp(System.currentTimeMillis()));
						tuser.setPasswd(MD5.MD5Encode(MD5.MD5Encode(pwd)));
						userId = tusersService.getUserID();
						tuser.setUserId(userId);
						tuser.setToken(token);
						dao.save(tuser);
						getSession().setAttribute("app_userid",tuser.getUserId());
						resultUserid = userId;
						resultToken = token;
					}else{
						result.put("code", "-1");
						result.put("msg", "手机号已存在，请重新登录或者检查手机号");
						return result;
					}
				}else{
					StringBuffer sb = new StringBuffer("from TUsers where userId='");
					sb.append(userId);
					sb.append("'");
					tuser = (TUsers) dao.loadObject(sb.toString());
					if (tuser==null || StringUtils.isBlank(tuser.getAppId())) {
						result.put("code", "-1");
						result.put("msg", "无法获取用户信息，请重新登录");
						return result;
					}else{
						resultUserid = tuser.getUserId();
						resultToken = tuser.getToken();
					}
				}


				if (StringUtils.isBlank(userId)) {
					result.put("code", "-1");
					result.put("msg", "无法获取用户信息，请重新登录");
					return result;
				}


				/*
  				StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
				where.append(" and agtCode ='");
				where.append(tCommunity.getAgtCode());
				where.append("'");
				AppStore appStores = (AppStore) appStoreService.get(where.toString());
				if(appStores==null || !(tuser.getAppId().equals(appStores.getAppId()))){
					result.put("code", "-1");
					result.put("msg", "APP无法获取");
					return result;
				}
				*/
				tCommunity.setAppId(tuser.getAppId());
			}else{
				StringBuilder where = new StringBuilder("from AppStore where 1=1 ");
				where.append(" and agtCode ='");
				where.append(tCommunity.getAgtCode());
				where.append("'");
				AppStore appStores = (AppStore) appStoreService.get(where.toString());
				if(appStores==null){
					result.put("code", "-1");
					result.put("msg", "厂商还未开放APP,暂时无法注册");
					return result;
				}
				tCommunity.setAppId(appStores.getAppId());
			}


			//同步到开发平台
			result = SyncTo(tCommunity);
			if (!"1".equals(result.get("code").toString())) {
		        throw new MdKnownRunTimeException((String)result.get("msg"));
		    }
			tCommunity.setPlatDepartId(result.get("departid").toString());
			String roleId = "5";//锁厂客户角色
			String status="1";//审核状态
			//新建管理员用户并增加到表
			result = addtCommunity(tCommunity,roleId,status,typeAPP);
			if (!"1".equals(result.get("code").toString())) {
				return result;
			}
			tCommunity = (TCommunity) result.get("tCommunity");
         	if(ifInstall){//硬件自动安装
         		StringBuffer where1 =new StringBuffer();
				where1.append(" pid='");
	   			where1.append(pid);
	   			where1.append("'");
         		TLock tlock = tLocksService.getHql(where1.toString());

         		result =tLocksService.installLock(tCommunity,tlock);
         		if (!"1".equals(result.get("code").toString())) {
       			 throw new MdKnownRunTimeException(result.get("msg").toString());
         		}
         		tlock.setCommunityId(Long.toString(tCommunity.getSid()));
         		tlock.setStatus("1");//设置已安装
         		tlock.setInstallLockName(lockName);
         		tlock.setInstallTime(new Timestamp(System.currentTimeMillis()));
         		update(tlock);
         		List list = new ArrayList();
				list.add(tlock);
				try{
					tKeysService.SyncTo(tuser, list, DateUtils.formatDate(DateUtils.addYear(new Date(), 20)), tlock.getAgtCode(), null);//分配一把20年的钥匙给用户
				}catch(Exception e){
					log.error(this,e);
				}
         	}

         	if("2".equals(type)){//转移之后，之前的钥匙都做失效处理
         		dao.updateBySql("update t06_keys set status='2' where pid='"+pid+"'");
         		dao.updateBySql("update topenlog set status='1' where pid='"+pid+"'");
         		dao.updateBySql("delete from t06_keys_prolong  where pid='"+pid+"'");
         	}
            result.put("objectId", tCommunity.getSid());
            result.put("code", 1);
            result.put("msg", "操作成功");
            result.put("token", resultToken);
            result.put("userid", resultUserid);
         } catch (MdKnownRunTimeException e) {
             log.error("社区保存失败", e);
             result.put("code", 0);
             result.put("msg", "注册成功，"+e.getMessage());
         }catch (Exception e) {
             log.error("社区保存失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
         }
		 return result;
	}


	public Map<String, Object> addtCommunity(TCommunity tCommunity, String roleId, String status, String typeAPP) {
		try {
			result = new HashMap<String, Object>();
			long idNext  = dao.findSequence("SEQ_T03_COMMUNITY");
			Map<String, Object> resultSysopt = sysOptService.creatComuManager(tCommunity,idNext+"",roleId,typeAPP);
			if (!"1".equals(resultSysopt.get("code").toString())) {
				result.put("code", 0);
				result.put("msg", resultSysopt.get("msg"));
				return result;
			}
			tCommunity.setSid(idNext);
			tCommunity.setAdminUser(resultSysopt.get("sid").toString());
			tCommunity.setComm("");
			tCommunity.setcTime(new Timestamp(System.currentTimeMillis()));
			tCommunity.setStatus(status);

			tCommunity = add(tCommunity);
			result.put("objectId", tCommunity.getSid());
			result.put("tCommunity", tCommunity);
			result.put("code", 1);
			result.put("msg", "操作成功");
		} catch (Exception e) {
			log.error("社区保存失败", e);
			result.put("code", 0);
			result.put("msg", "操作失败");
		}
		return result;
	}

	@Override
	@LogAnnotation(operateDescribe="小区审核")
	public Map<String, Object> auditMethod(String sid, String status, String appSid,String comm) throws Exception {
		 result.put("objectId", sid);
		 Sysopt  user= (Sysopt)getSession().getAttribute("user");
		 TCommunity tCommunity = get(Long.parseLong(sid));
		 //更新tCommunity数据
		 tCommunity.setStatus(status);
		 tCommunity.setComm(comm);
		 if ("-1".equals(user.getIsAdmin())) {
			 TAgent tagent =  tAgentService.get(tCommunity.getAgtCode());
			 tCommunity.setaUserName(tagent.getAdminUser());
			 tCommunity.setOperateComm("平台超级管理员操作");
		 }else{
			 tCommunity.setaUserName(Long.toString(user.getSid()));
		 }
		 tCommunity.setaTime(new Timestamp(System.currentTimeMillis()));
		 if ("1".equals(status) && StringUtils.isNotBlank(appSid)) {
			 tCommunity.setAppId(appSid);
		 }
         update(tCommunity);
         if (!"1".equals(status)) {//拒绝或者候审状态
			 result.put("code", 1);
	         result.put("msg", "操作成功");
	         return result;
		 }
         //同步数据到开放平台
         result = SyncTo(tCommunity);
         if (!"1".equals(result.get("code").toString())) {
        	 throw new MdKnownRunTimeException((String)result.get("msg"));
         }
         tCommunity.setPlatDepartId(result.get("departid").toString());
         update(tCommunity);

		 //创建社区超级管理员角色
		 result = sysRolesTemplateService.creatComuManager(tCommunity);
		 if ("0".equals(result.get("code").toString())) {
			 return result;
		 }
		 //更新超级管理员角色权限
		 sysOptService.updateManager(tCommunity.getAdminUser(),result.get("roleId").toString());
		 result.put("code", 1);
	     result.put("msg", "操作成功");
		 return result;
	}

	/**
	 * @Description: 同步社区信息到开放平台
	 * @param entity
	 * @return
	 */
	public Map<String, Object> SyncTo ( TCommunity tCommunity){
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String,String> map = tAgentService.getPlatAppKey(tCommunity.getAgtCode());
			MdOpenAddCommunityJson json = MdOpenApi.addCommunity(tCommunity,map.get("agt_num"),map.get("app_key"));
			if(json.isSuccess()){
				if ("0".equals(tCommunity.getType())) {
					tCommunity.setPlatDepartId(json.getData().getDepartid());
					update(tCommunity);
				}
				result.put("departid", json.getData().getDepartid());
				result.put("code", 1);
      	        result.put("msg", "操作成功");
			}else{
				log.error("同步社区信息到开放平台失败，json:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
				result.put("code", 0);
      	        result.put("msg", "社区审核成功，同步失败:"+json.getMsg().toString().replaceAll("[^0-9\\u4e00-\\u9fa5]", ""));
			}
    	} catch (Exception e) {
    		log.error("同步社区信息到开放平台失败", e);
    		result.put("code", 0);
  	        result.put("msg", "同步社区信息到开放平台失败");
    	}
		return result;
	}

	@Override
	public TCommunity get(String where) {
		String sql  = "from TCommunity where "+where;
		return (TCommunity) dao.loadObject(sql);
	}

	@Override
	public List<TCommunity> auditList(JqGridPager page,String agtCode) {
		Sysopt  user= (Sysopt)getSession().getAttribute("user");
		int userRole =  (Integer) getSession().getAttribute("userRole");
		StringBuffer sb  = new StringBuffer();
		sb.append("select * from (");
		if (userRole == 1) {
			sb.append("select t.sid,a.agtname,t.communityName,t.cityCode,TO_CHAR (t.atime,'YYYY-MM-DD hh24:mi:ss') atime,TO_CHAR (t.ctime,'YYYY-MM-DD hh24:mi:ss') ctime,t.comContact,t.departTel,t.street,t.status,'('||t.operatecomm||')'||t.comm as comm,s.username as adminUser,n.uname as auserName ");
		}else{
			sb.append("select t.sid,a.agtname,t.communityName,t.cityCode,TO_CHAR (t.atime,'YYYY-MM-DD hh24:mi:ss') atime,TO_CHAR (t.ctime,'YYYY-MM-DD hh24:mi:ss') ctime,t.comContact,t.departTel,t.street,t.status,t.comm,s.username as adminUser,n.uname as auserName ");
		}
		sb.append(" from "
				+ "t03_community t "
				+ "left join sysopt s on ( t.adminuser = s.sid) "
				+ "left join sysopt n on ( t.ausername = n.sid) "
				+ "left join t02_agtent a on (t.agtcode = a.sid)");

		if(userRole == 5 || userRole == 6){
			return null;
		}else{
			sb.append("where t.agtCode ='");
			sb.append(agtCode);
			sb.append("'");
		}
		sb.append(" and (t.status='0' or t.status='3') order by t.ctime desc)");
		sb.append(" union all ");
		sb.append("select * from (");
		if (userRole == 1) {
			sb.append("select t.sid,a.agtname,t.communityName,t.cityCode,TO_CHAR (t.atime,'YYYY-MM-DD hh24:mi:ss') atime,TO_CHAR (t.ctime,'YYYY-MM-DD hh24:mi:ss') ctime,t.comContact,t.departTel,t.street,t.status,'('||t.operatecomm||')'||t.comm as comm,s.username as adminUser,n.uname as auserName ");
		}else{
			sb.append("select t.sid,a.agtname,t.communityName,t.cityCode,TO_CHAR (t.atime,'YYYY-MM-DD hh24:mi:ss') atime,TO_CHAR (t.ctime,'YYYY-MM-DD hh24:mi:ss') ctime,t.comContact,t.departTel,t.street,t.status,t.comm,s.username as adminUser,n.uname as auserName ");
		}
		sb.append(" from "
				+ "t03_community t "
				+ "left join sysopt s on ( t.adminuser = s.sid) "
				+ "left join sysopt n on ( t.ausername = n.sid) "
				+ "left join t02_agtent a on (t.agtcode = a.sid)");
		sb.append("where t.agtCode ='");
		sb.append(agtCode);
		sb.append("'");
		sb.append(" and (t.status='1' or t.status='2') order by t.ctime desc)");
		return dao.query(sb.toString(), page);
	}

	@Override
	public List<TCommunity> listByAgtCodes(String agtCodes) {
		List<TCommunity> TCommunitys = new ArrayList<TCommunity>();
    	List<String> listArr = new ArrayList<String>();
    	if (StringUtils.isNotBlank(agtCodes)) {
    		String[] arr = agtCodes.split(",");
    		listArr = Arrays.asList(arr);
	    }else{
	    	return TCommunitys;
	    }
    	final List<Long> rids = new LinkedList<Long>();
    	for (String str : listArr) {
			rids.add(Long.parseLong(str));
		}
		if (rids != null) {
             String sql = "from TCommunity where agtCode in (:ids)";
             TCommunitys = dao.executeFindS(sql,"ids",listArr);
		}
		return TCommunitys;
	}



//todo ---------------------------------------------------------------------------------------------------


	/**
	 * 小区列表（下拉）
	 *
	 * @param agtCode  合作方id
	 * @param user     当前用户
	 * @param userRole 当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/2 下午1:44
	 */
	@Override
	public List<TCommunitySelectVO> selectList(String agtCode, Sysopt user, int userRole) {

		String communityId = null;
		Long sysoptId = null;

		if (userRole == 5 || userRole == 6) {
//			where.append(" and t.sid ='");
//			where.append(user.getCommunityId());
//			where.append("'");
			communityId = user.getCommunityId();
		}
		if (StringUtils.isBlank(agtCode)) {
			if (userRole == 3 || userRole == 4) {
//				where.append(" and t.agtCode ='");
//				where.append(user.getAgtCode());
//				where.append("'");
				agtCode = user.getAgtCode();
			}else if (userRole == 21) {
//				where.append(" and a.sysoptId =");
//				where.append(user.getSid());
				sysoptId = user.getSid();
			}
		}else{
//			where.append(" and t.agtCode ='");
//			where.append(agtCode);
//			where.append("'");
		}
		return tCommunityDao.selectList(communityId,agtCode,sysoptId,userRole);
	}
}
